package org.example.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class SocketClient {
    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in);
        Socket socket = new Socket("localhost",8888);
        socket.setKeepAlive(true);
        InputStream is;
        OutputStream os;
        is = socket.getInputStream();
        os = socket.getOutputStream();
        //业务数据
        String str = input.next();
        os.write(getBytes(str));
        byte[] bytes = new byte[1024];
        while (is.read(bytes) != -1){
            System.out.println(new String(bytes).trim());
            str = input.next();
            os.write(getBytes(str));
            os.flush();
        }

    }

    public static byte[] getBytes(String msg){
        byte[] msgByte = msg.getBytes(StandardCharsets.UTF_8);
        int msgLength = msgByte.length;
        byte[] bytes = new byte[msgLength+7];
        bytes[0] = (byte) 0x28;
        byte[] length = (msgLength+"").getBytes();
        int lengthLen = length.length;
        for (int i = 1; i < 5-lengthLen; i++) {
            bytes[i] = (byte) 48;
        }
        System.arraycopy(length, 0, bytes,5-lengthLen , lengthLen);
        System.arraycopy(msgByte,0,bytes,5,msgLength);
        bytes[5+msgLength] = (byte) 0x00;
        bytes[6+msgLength] = (byte) 0x29;
        return bytes;
    }
}
